﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using Monocle.DataModel;
using Monocle.DataProvider;

namespace Monocle.Infrastructure.Account
{
    public class AccountRoleProvider : RoleProvider
    {
        private SqlClient dataProvider;
        public AccountRoleProvider()
        {
            dataProvider = AccountDataAccess.DataProvider();
        }

        public override bool IsUserInRole(string username, string roleName)
        {
            if (string.IsNullOrEmpty(username))
            {
                return false;
            }
            if (string.IsNullOrEmpty(roleName))
            {
                return false;
            }
            var user = dataProvider.GetUserByEmail(username);
            return dataProvider.GetUsersRoles(user).Any(x => x.Name == roleName);
        }

        public override string[] GetRolesForUser(string username)
        {
            var user = dataProvider.GetUserByEmail(username);
            var userRole = dataProvider.GetUsersRoles(user);
            return userRole.Select(role => role.Name).ToArray();
        }

        public override void CreateRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            throw new NotImplementedException();
        }

        public override bool RoleExists(string roleName)
        {
            throw new NotImplementedException();
        }

        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            var user = dataProvider.GetUserByEmail(usernames[0]);
            var allRoles = dataProvider.GetUserRoles();
            List<Guid> roles = (from r in allRoles from s in roleNames where r.Name == s select r.PK_tUserRole).ToList();
            dataProvider.SetUserRoles(user, roles);
        }

        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override string[] GetUsersInRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override string[] GetAllRoles()
        {
            return dataProvider.GetUserRoles().Select(role => role.Name).ToArray();
        }

        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            throw new NotImplementedException();
        }

        public override string ApplicationName
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }
    }
}